import router from '@system.router'
import storage from '@system.storage'
import fetch from '@system.fetch'
import md5 from "/src/global/md5.js";
import prompt from '@system.prompt'
import device from '@system.device'
function redirect(uri,params,isReplace){
  if(uri === 'back'){
    router.back();
  }else{
    if(!isReplace){
      router.push({
        uri: uri,
        params: params
      })
    }else{
      router.replace({
        uri: uri,
        params: params
      })
    }
  }
}

// 同步获取缓存数据
 async function cget(key){
    let rs = false;
    let data = await storage.get({key: key});
    console.log('cget:'+key,data);
    if(data.data){
      data = data.data;
      data = JSON.parse(data);
      if(!data.isExpire){
        rs = data.data; 
      }else{
        var timestamp = Date.now();
        if(data.expire - timestamp >= 0){
          rs = data.data;
        } 
      }
    }
    return rs;
}

  async function ccget(key) {
    let rs = await storage.get({key: key});
    console.log('rs',rs);
    return rs;
  
}

async function cset(key,data,outTime){
   console.log('cset:'+key);
    outTime = outTime?outTime:0;
    let isExpire = outTime !== 0;
    var timestamp = Date.now();
    var cacheData = {isExpire:isExpire,expire:timestamp + outTime*1000,data:data};
    await storage.set({
        key: key,
        value: cacheData,
        success: function(data) {
          // console.log('handling success')
        },
        fail: function(data, code) {
          // console.log(`handling fail, code = ${code}`)
        }
      })
}
async function userToken(){
  let cache = await $xt.cget('utoken');
  if(!cache){
    let timestamp = Date.now();
    let uinfo = {uid:Math.random().toString(36).substr(2),utime:parseInt((timestamp/1000).toString()),coins:0}
    await cset('utoken',uinfo);
    $xConfig.uinfo = uinfo;
  }else{
    $xConfig.uinfo = cache;
  }  
  return $xConfig;
}
function getSignParams(params){
  let ts = Math.round(new Date().getTime()/1000).toString();
  let sign = ts.substr(-4);
  const authParam = {"ts":ts,"sign":md5.hex_md5(sign)}
  return Object.assign(params,authParam);
}
// request get请求
async  function rfetch(path,params){
  let aConfig = await userToken();
  let url = path.includes('http')? path: aConfig.rootHost+path;
  let requestParams = {
    uuid: aConfig.uinfo.uid,
    app_name: aConfig.appName,
    app: aConfig.app,
    current_page:getPath(),
    app_version:aConfig.appVersion,
    utime:aConfig.uinfo.utime,
    oaid:await getOaid()
  };
  requestParams = Object.assign(requestParams,params)
  requestParams = getSignParams(requestParams);
  let resData = {code:0,data:''};
  console.log('request_url',url,requestParams);
  let response = await  fetch.fetch({
    url: url,
    data:requestParams,
    responseType: 'json'
  });
  console.log('response_url',url,response);
  if(response.data.code == 200){
    resData = response.data.data;
  }
  return resData;
}

function objToArr(obj){
  let nList = [];
  for(var i in obj){
    if(i !== undefined  && obj[i] !== {}){
      nList.push(obj[i]);
    }
  }
  return nList;
}
function toast(msg){
  prompt.showToast({
    message: msg
  })
}
async function userCoinsRecord(coins,remark){
  var userInfo = await this.getUserInfo();
  console.log('userInfo',userInfo);
  coins = parseInt(coins);
  if(!userInfo.coins){
    userInfo.coins = 0;
  }
  userInfo.coins = userInfo.coins + coins;
  if(userInfo.coins < 50000){
      this.setUserInfo(userInfo);
      var xCoinsRecord = await this.cget('xCoinsRecord');
      xCoinsRecord = xCoinsRecord?xCoinsRecord:[];
      var time = Date.now();
      var row = {coins:coins,remark:remark,time:time};
      xCoinsRecord.push(row)
      this.cset('xCoinsRecord',xCoinsRecord);
  }
}
async function setUserInfo(userInfo){
  this.cset('utoken',userInfo);
}
async function getUserInfo(){
  let userInfo = {};
  let cacheUserInfo = await $xt.cget('utoken');
  if(cacheUserInfo){
    userInfo = cacheUserInfo;
  }
  return cacheUserInfo;
}
 //JS睡眠sleep()  毫秒
 function sleep(numberMillis) {
  console.log("sleeep");
  var now = new Date();
  var exitTime = now.getTime() + numberMillis;
  while (true) {
      now = new Date();
      if (now.getTime() > exitTime){
          return;
      }
  }
}
// 获取页面路径
function getPath(){
  let rt = router.getState();
  return rt.path;
}
// 给金币
async function giveCoins(key,coins,remark){
  let cacheCoins = await $xt.cget(key);
  if(!cacheCoins){
    cacheCoins = 0;
  }
  var tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(0, 0, 0, 0);
  var tomorrowTimestamp = tomorrow.getTime();
  var timestamp = Date.now();
  await $xt.cset(key,(parseInt(cacheCoins)+1),(tomorrowTimestamp-timestamp)/1000);
  await $xt.userCoinsRecord(coins,remark);
}
function xRand(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
 * 获取ads广告列表
 */
async function getAds(type){
  if(type === 'native'){
    // return 'PFGfvNZ4g17';
  }
  let aid = '';
  let adList = [];
  let cacheConfig = await $xt.cget('ads_ad_'+type);
  if(cacheConfig){
    adList = cacheConfig;
  }else{
    let remoteUrl = 'http://cdn.yqdhz.com/jingyue/app/'+$xConfig.app+'/huawei/ad/'+type+'.html';
    let res = await $xt.rfetch(remoteUrl);
    adList = res.data;
    $xt.cset('ads_ad_'+type,adList,60);
  }
  if(adList[0]){
    let length = adList.length;
    let randIndex = $xt.xRand(0,length-1);
    aid = adList[randIndex];
  }
  return aid;
}

async function xRemouteCheck(e){
    let hapString = JSON.stringify(e);
    $xt.cset('xhap',hapString);
    let remoteUrl = 'api/'+$xConfig.app+'.check_'+$xConfig.producer+'/';
    let checkRes = await $xt.rfetch(remoteUrl,{hap:hapString});
    if(checkRes.code === 1){
      let check = checkRes['data'];
      return check;
    }
    return {}
   
}
// 获取广告位id
async function getOaid(){
  let cacheOaid = await cget('oaid');
  if(cacheOaid){
    return cacheOaid;
  }else{
    let oaid = '';
    let deviceOaid = await device.getDeviceId()
    if(deviceOaid.data && deviceOaid.data.deviceId){
      oaid = deviceOaid.data.deviceId;
    }
    await cset('oaid',oaid);
    return oaid;
  }
}

async function extraConfig(type){
  let remoteUrl = 'api/'+$xConfig.app+'.extra'+$xConfig.producer+'/wxPath';
  let res = await $xt.rfetch(remoteUrl);
  return res;
}

// 给金币
export default {
  userToken,redirect,cget,cset,rfetch,ccget,objToArr,toast,userCoinsRecord,setUserInfo,getUserInfo,sleep,getPath,giveCoins,xRand,xRemouteCheck,getOaid,getAds,extraConfig
}
